//
//  String+Extension.swift
//  Game
//
//  Created by woniu on 2025/8/28.
//

import Foundation
extension String{
    
    //JSONString转换为数组
    func getArrayFromJSONString() ->[Any]{
        guard let jsonData:Data = self.data(using: .utf8) else{
            return []
        }
        if let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [Any] {
            return array
        }
        return []
    }
    
    ///String 转 字典
    func toDic()->[String:Any]{
        if self.isEmpty{return[:]}
        guard let data = self.data(using: String.Encoding.utf8)else{return [:]}
        var tempDic:[String:Any] = [:]
        if let dict = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String : Any] {
            tempDic = dict
        }
        if !tempDic.isEmpty{return tempDic}
        //字符串里的字符串转dic
        guard let dic = try? JSONSerialization.jsonObject(with:data, options: .allowFragments) as? [String:Any] ?? [:] else {
            let beginStr = "\"{"
            let endStr = "}\""
            let str = self
            if str.hasPrefix(beginStr) && str.hasSuffix(endStr){
                let subStr = str.subString(from: 1, to: 2)
                guard let vDic = try? JSONSerialization.jsonObject(with: subStr.data(using: .utf8)!, options: .allowFragments) as? [String:Any] ?? [:] else {
                    return [:]
                }
                return vDic
            }
            
            return [:]
        }
        return dic
    }
    
    /// 从任意位置开始截取到任意位置 (包含to )
    func subString(from: Int, to: Int) -> String {
        let beginIndex = self.index(self.startIndex, offsetBy: from)
        let endIndex = self.index(self.startIndex, offsetBy: to)
        return String(self[beginIndex...endIndex])
    }
}
